<template>
  <div>
<el-dialog
  width="45%"
  :visible.sync="showDialog"
  :close-on-click-modal="false"
>
  <CommonForm
    :form-config="dialogFormConfig"
    :form-label="dialogFormLabel"
    :form="dialogForm"
  ></CommonForm>
<span slot="footer">
  <el-button type="primary" @click="userAddForm(dialogForm)" >确定</el-button>
  <el-button @click="showDialog = false">取消</el-button>
</span>
</el-dialog>
    <h4>用户管理</h4>
    <div class="searchArea">
      <CommonForm
        :form="searchForm"
        :formLabel="searchLabel"
        :formConfig="searchConfig"
      >
        <div class="btnGroup">
          <el-button type="primary" icon="el-icon-search" @click="searchCommit(searchForm)">检索</el-button>
          <el-button  icon="el-icon-plus" @click="showDialog = true" type="primary" plain>添加</el-button>
          <el-popconfirm
            :title="tableSelected.length<=0?'未选择用户':'确定删除该用户？'"
            @confirm="()=>{tableSelected.length<=0?this.$notify.warning('未选择用户！'):deleteUsers(this.tableSelected)}"
          >
            <el-button style="margin-left: 0.5rem" slot="reference" icon="el-icon-delete"  type="danger" plain>删除</el-button>
          </el-popconfirm>
        </div>
      </CommonForm>
    </div>
    <div class="tableArea">
      <CommonTable
        style="height: 380px"
        v-if="tableConfig.isShowTable"
        :tableData="tableData"
        :tableLabel="tableLabel"
        :tableConfig="tableConfig"
        v-loading = "tableConfig.loading"
        @sizeChange="getTableData(1, tableConfig.size, {})"
        @currentPage="getTableData(tableConfig.page, tableConfig.size, {})"
        @handleSelectionChange="handleSelectionChange"
      ></CommonTable>
      <el-empty v-else></el-empty>
    </div>
  </div>
</template>

<script>
import CommonForm from "@/components/common/CommonForm";
import {getProviderNameId} from "@/api/systemManage/organizationManage";
import {addUser, getUserList,deleteUser} from "@/api/systemManage/userManage";
import Vue from "vue";
import CommonTable from "@/components/common/CommonTable";


export default {
  components: {CommonForm,CommonTable},

  created() {
    getProviderNameId().then(res=>{
      const result = res;
      if (result.code = 200){
        const data = result.data.data;
        // console.log(data)
        let arr =[];
        data.forEach((item)=>{
          let {city:label,city:value} = item;
          let children=[];
          const itemList = item.areaList;
          for (let i of itemList){
            // console.log(i)
            let {providerName:label,providerId:value} = i
              children.push({label,value});
          }

          arr.push({label,value,children});
        })
        Vue.set(this.searchLabel,'1',{
          label: '组织',
          model: "providerName",
          type:'cascader',
          options:arr      //服务商id和名称
        });
      }
    });
  },
  beforeMount() {
    this.getTableData(1,10,{})
  },
  data(){
    const checkPhone = (rule, value, callback)=>{

      const pattern  = /^1[3456789]\d{9}$/;
      if (!pattern.test(value)){
        return  callback(new Error('请检查手机格式'))
      }
      else {
       return  callback();
      }
    };
    const checkEmail=(rule,value,callback)=>{
      const pattern  = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
      if (!pattern.test(value)){
        callback(new Error('请检查邮箱格式'))

      }else {
        return  callback()
      }
    }
    return{
      /*------------------dialog部分-------------------*/
      showDialog:false,
      dialogForm:{
        account: '',//账号
        username:'',//用户名
        providerID:'',//所属组织
        role:'',//角色
        phone:'',//手机号
        landline:'',//座机号
        email:'',//邮箱
        remark:''//备注
      },
      dialogFormLabel:[
        {
          label:'账号',
          model:'account',
          width:'70'
        },
        {
          label: '用户名',
          model: 'username',
          width:'70'
        },
        {
          label: '所属组织',
          model: 'providerID',
          // width:'70',
          type:'select'
        },
        {
          label: '角色',
          model: 'role',
          // width:'70',
          type:'select'

        },
        {
          label: '手机号',
          model: 'phone',
          width:'70'
        },
        {
          label: '座机号',
          model:'landline',
          width:'70'
        },
        {
          label: '邮箱',
          model: 'email',
          width:'70'
        },
        {
          label: '备注',
          model: 'remark',
          width:'80',
          type: "textarea",
          rows: 5,
        }
      ],
      dialogFormConfig:{
        labelWidth: "100px",
        inline: false,
        labelPosition: "right",
        rules: {
          phone:[
            {validator:checkPhone,trigger:'blur'}
          ],
          email:[
            {validator:checkEmail,trigger:'blur'}
          ]
        }
      },
      /*------------------检索部分-------------------*/
      searchForm:{
        keyword:'',//关键字
        providerName:'',//组织名
        role:'',//角色
        isAdmin:'',//管理员

      },
      searchLabel:[
        {
          label:'关键字',
          model:'keyword',
          labelWidth:'60px'
        },
        {
          label: '组织',
          model: "providerName",
          type:'cascader',
          options:[]      //服务商id和名称
        },
        {
          label: "角色",
          model: "role",
          type:'select',

        },
        {
          label: "管理员",
          model: "isAdmin",
          type:'select',
          labelWidth:'60px',
          options:[
            {
              value:2,
              label:'全部人'
            },
            {
              value:0,
              label:'全部管理员'
            },
            {
              value:1,
              label:'其他人'
            }
          ]
        }
      ],
      searchConfig: {
        labelWidth: "40px",
        inline: true,
        labelPosition: "left",
      },
      /*------------------表格部分-------------------*/
      tableData:[

      ],
      tableLabel:[
        {
          prop:'webUserId',
          label:'用户ID'
        },
        {
          prop:'account',
          label:'账号'
        },
        {
          prop:'userName',
          label:'用户号名'
        },
        {
          prop:'isAdmin',
          label:'管理员',
          type:'dualJudgment',
          trueType:'是',
          falseType:'否'
        },
        {
          prop:'phone',
          label:'手机号'
        },
        {
          prop:'landline',
          label:'座机'
        },
        {
          prop:'email',
          label:'邮箱'
        },
        {
          prop:'remark',
          label:'备注'
        },
        {
          prop:'roleName',
          label:'角色'
        },
        {
          prop:'providerName',
          label:'服务商'
        },
      ],
      tableConfig:{
        isShowTable:false,
        isShowLoading:true,
        page:1,
        total:30,
        size:10,
        loading:true,
        selection:true
      },
      tableSelected:[]//表格选中合集
    }
  },
  methods:{
    getTableData(page,pageSize,datas){
      this.tableConfig.isShowTable = true;
      getUserList(page,pageSize,datas).then(res=>{
        const result = res.data;
        const userData = result.data.records||[];//用户信息列表
        if (result.code == 200 && userData.length > 1){
          this.tableConfig.isShowTable = true;
          this.tableConfig.loading = false;
          this.tableData  = userData;
          this.tableConfig.total = result.data.total;
          this.tableConfig.size = result.data.size;
          this.tableConfig.page = result.data.current;
        }
        else{
          this.tableConfig.isShowTable = false;
          this.tableConfig.loading = false;
          this.$notify.info('暂无用户数据')
        }
      }).catch(err=>{
        console.log(err);
        this.$notify.error('网络出错，请查看控制台');
      })
    },
     searchCommit(form){
       this.getTableData(1,this.tableConfig.size,form)
    },
    userAddForm(data){
      addUser(data).then(res=>{

      })
    },
    //table section 表格选中事件
    handleSelectionChange(val){
      this.tableSelected = val
    },
   async deleteUsers(delList){
      let fileCount = 0;
      for (const item of delList) {
        await deleteUser(item.webUserId).then((res)=>{
          const resulat = res.data;
          if (resulat.success !== true){
            fileCount++;
          }
        }).catch(error=>{
          fileCount++;
          console.log(error);
          this.$message.error('请求失败，请查看控制台')
        })
      }
      fileCount<0?this.$notify.success(`成功删除${delList.length}位用户`):this.$notify.warning(`成功删除${delList.length-fileCount}位用户,未能删除${fileCount}位用户`)
      this.getTableData(1,10,this.searchForm)
   }
  },
  watch:{
    'showDialog' (newValue){
     if (!newValue){
       this.dialogForm = this.$options.data().dialogForm;
     }
    }
  }
}
</script>

<style>
.btnGroup{
  position: relative;
  bottom: 0.75rem;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
@media screen and (min-width:1060px) and (max-width: 1333px){
.btnGroup{
  float: right;
  transform: translateY(0.5rem);
  }
}
@media screen and (max-width: 840px) {
  .btnGroup{
    float: left;
  }
}
</style>
